#!/bin/bash

. $ZMICRO_HOME/core/env

update_zmicro() {
  local origin_version=$(version::get)
  # log::update PREV

  # @TODO add auto update
  # zmicro auto update

  log::update CORE zmicro START

  cd $ZMICRO_HOME
  git pull origin master >>$ZMICRO_LOG_UPDATE_PATH 2>>$ZMICRO_LOG_ERROR_PATH # 2>&1
  if [ "$?" != "0" ]; then
    echo "Update ZMicro Error, see $ZMICRO_LOG_UPDATE_PATH"
    tail -n 50 $ZMICRO_LOG_ERROR_PATH
    exit -1
  fi

  # log::update LATEST
  local new_version=$(version::get)

  log::version $origin_version $new_version

  # log::timestamp "[LATEST_VERSION] ${ZMICRO_VERSION}"

  # update depdendencies
  require::core_mod -u

  # Auto Register After Update
  plugin::register_all $ZMICRO_PLUGINS_PATH

  log::update CORE zmicro END
}

help() {
  echo "update zmicro"
  echo ""
  echo "Usage:"
  echo "  zmicro update [self | plugin_name] [...options]"
  # echo "    -p, --plugin <plugin_name | all>    Update all or one plugin"
  echo "    -a, --all   Update core and all plugins"
}

core() {
  if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
    help
    exit 0
  fi

  local plugin_name=""
  while [[ $# -gt 0 ]]; do
    local key=$1
    local value=$2
    case $key in
    -h | --help)
      help
      exit 0
      ;;
    # -p | --plugin)
    #   if [ -z "$value" ]; then
    #     log::error "plugin name is required"
    #     exit 1
    #   fi

    #   os::set_var plugin_name $value
    #   shift
    #   shift
    #   ;;
    -a | --all)
      os::set_var update_all true
      shift
      ;;
    *)
      if [ "$(string::match $key ^-)" = "true" ]; then
        echo "ERROR: unknown parameter \"$key\""
        help
        exit 1
      fi

      if [ -z $plugin_name ]; then
        plugin_name=$key
      fi
      shift
      ;;
    esac
  done

  if [ -n "$plugin_name" ]; then
    if [ "$plugin_name" = "self" ]; then
      update_zmicro
    else
      zmicro plugin update $plugin_name
    fi
  elif [ "$update_all" = "true" ]; then
    update_zmicro
    zmicro plugin update
  else
    update_zmicro
  fi
}

run() {
  core $@
}

run $@
